﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using QuickAppLibrary;

namespace WebApplicationFiller
{
    public partial class AppFillerSubForm : Form
    {
        //Class Objects/Varibles
        private ApplicationInfo appInfo;
        private string appInfoPath = "AppInfo.info";
        private string resumePath = "Resume.info";
        private string coverPath = "Cover.info";
        private string priorPath = "Prior.info";
        private string file = "";
        private PriorEmployerCollection empColl;

        //Constructor
        public AppFillerSubForm()
        {
            //Construct new objects here
            appInfo = new ApplicationInfo();
            empColl = new PriorEmployerCollection();
            InitializeComponent();
            LoadAppFiles();
        }

        //Events
        private void acceptButton_Click(object sender, EventArgs e)
        {
            //Add class info
            AddClassRef();
            
            //Save info to file
            SaveFileControls(appInfoPath, AppTabPage.Controls);

            //Save Resume info to file
            SaveFile(resumePath, resumeRichTextBox);

            //Save Cover letter info to file
            SaveFile(coverPath, coverRichTextBox);

            //Save Collection to XML File
            empColl.SerializeToFile(priorPath);

            //DO NOT CLOSE THE FORM! It is dependant on the MainForm
            this.Hide();

        }

        //Class Methods
        //Method for Get Application info
        public ApplicationInfo getAppInfo()
        {
            return appInfo;
        }

        //Method for get prior employeer collection
        public PriorEmployerCollection getPriorEmpColl()
        {
            return empColl;
        }

        //Method for Load file
        public void LoadAppFiles()
        {
            //Load file for AppInfo file
            OpenFileControls(appInfoPath, AppTabPage.Controls, ref file);

            //Load Resume file
            OpenFileAndRead(resumePath, resumeRichTextBox, ref file);

            //Load 
            OpenFileAndRead(coverPath, coverRichTextBox, ref file);

            //Add each property
            AddClassRef();

            //Load Info for prior employment
            empColl.DeserizlizeFromFile(priorPath);

            //Add Prior Employeer to listBox
            AddPriorList();

        }

        private void AddPriorList()
        {
            foreach (PriorEmployer emp in empColl)
            {
                employersListBox.Items.Add(emp.ToString());
            }
        }

        //Replace with XML Seriealizer?!
        //Method for getting file data
        private void OpenFileAndRead(string path, RichTextBox textObj, ref string file)
        {
            //Clear file
            file = "";
            if (File.Exists(path))
            {
                using (StreamReader sr = File.OpenText(path))
                {
                    while (!sr.EndOfStream)
                    {
                        try
                        {
                            file += sr.ReadLine() + "\n";
                        }
                        catch (ArgumentOutOfRangeException ex)
                        {
                            //Error
                            MessageBox.Show(ex.StackTrace);
                        }
                    }
                    //Apend info to Textbox
                    textObj.Text = file;

                    //Clear file string
                    file = "";
                }
            }
        }

        //Replace with XML Seriealizer?!
        //Method for getting file data for controls
        private void OpenFileControls(string path, Control.ControlCollection con, ref string file)
        {
            if (File.Exists(path))
            {
                using (StreamReader sr = File.OpenText(path))
                {
                    while (!sr.EndOfStream)
                    {
                        try
                        {
                            file = sr.ReadLine();
                            string contrl = file.Substring(0, file.IndexOf("="));
                            string fileval = file.Substring(file.IndexOf("=") + 1);

                            //Loop through each control to find a match
                            foreach (Control c in con)
                            {
                                if (c.Name == contrl)
                                {
                                    c.Text = fileval;
                                }
                            }
                        }
                        catch (ArgumentOutOfRangeException ex)
                        {
                            //Error
                            MessageBox.Show(ex.StackTrace);
                        }
                    }
                }
            }
        }

        //Replace with XML Seriealizer?!
        //Method for saving file data
        private void SaveFile(string path, RichTextBox textObj)
        {
            using (StreamWriter sw = new StreamWriter(File.Open(path, FileMode.Create), Encoding.Unicode))
            {
                sw.WriteLine(textObj.Text);
            }
        }

        //Replace with XML Seriealizer!
        //Method for saving file data for controls
        private void SaveFileControls(string path, Control.ControlCollection con)
        {
            using (StreamWriter sw = File.CreateText(path))
            {
                //Loop through each text field
                foreach (Control c in con)
                {
                    if (c is TextBox || c is DateTimePicker)
                    {
                        sw.WriteLine(c.Name + "=" + c.Text);
                    }
                }
            }
        }

        //Method for adding class references
        private void AddClassRef()
        {
            //Add Phone Contact Info
            appInfo.cellPhone = this.cellTextBox.Text;
            appInfo.mainPhone = this.phoneTextBox.Text;
            appInfo.workPhone = this.workTextBox.Text;

            //Add Address Info
            appInfo.street = this.addrL1TextBox.Text;
            appInfo.street2 = this.addrL2TextBox.Text;
            appInfo.city = this.cityTextBox.Text;
            appInfo.state = this.stateTextBox.Text;
            appInfo.zip = this.zipTextBox.Text;

            //Add Basic Contact info
            appInfo.firstName = this.fNameTextBox.Text;
            appInfo.lastName = this.lNameTextBox.Text;
            appInfo.middleName = this.midNameTextBox.Text;
            appInfo.email = this.emailTextBox.Text;

            //School info
            //High School
            appInfo.highSchool = this.hsTextBox.Text;
            appInfo.highSchoolCity = this.hsCityTextBox.Text;
            appInfo.highSchoolState = this.hsStateTextBox.Text;

            //College
            appInfo.college = this.collegeTextBox.Text;
            appInfo.collegeCity = this.collegeCityTextBox.Text;
            appInfo.collegeDegree = this.collegeDegreeTextBox.Text;
            appInfo.collegeState = this.collegeStateTextBox.Text;
            appInfo.collegeMajor = this.collegeMajorTextBox.Text;

            //Other school degree
            appInfo.otherSchool = this.otherTextBox.Text;
            appInfo.otherSchoolCity = this.otherCityTextBox.Text;
            appInfo.otherSchoolDegree = this.otherDegreeTextBox.Text;
            appInfo.otherSchoolState = this.otherStateTextBox.Text;
            appInfo.otherSchoolMajor = this.otherMajorTextBox.Text;

            //Other info
            appInfo.availDate = this.availablityDateTimePicker.Value;
            appInfo.desiredSalary = this.desiredSalaryTextBox.Text;

            //Resume Text
            appInfo.resumeText = this.resumeRichTextBox.Text;

            //Cover Letter
            appInfo.coverLetter = this.coverRichTextBox.Text;
        }

        private void businessAddButton_Click(object sender, EventArgs e)
        {
            //Create an PriorEmployer Object
            PriorEmployer priorEmp;

            //Assign each property from the form
            priorEmp = new PriorEmployer(businessTextBox.Text, businessTypeTextBox.Text, 
                                         businessAddr1TextBox.Text, businessAddr2TextBox.Text, businessCityTextBox.Text, 
                                         businessStateTextBox.Text, businessZipTextBox.Text, 
                                         businessTitleTextBox.Text, businessManagerTextBox.Text,
                                         businessPhoneTextBox.Text, businessSalaryTextBox.Text, 
                                         businessReasonTextBox.Text, businessResponsTextBox.Text,
                                         businessFromDateTimePicker.Value, businessToDateTimePicker.Value);

            //Add it to the collection
            empColl.Add(priorEmp);

            //Add to Employeers List Box
            employersListBox.Items.Add(priorEmp.ToString());
        }

        //Remove Prior Employer
        private void businessRemoveButton_Click(object sender, EventArgs e)
        {
            //Get selected item from listbox
            string selectedEmp = (string)employersListBox.SelectedItem;

            //Remove from collection
            foreach (PriorEmployer emp in empColl)
            {
                //If match is found remove current
                if (emp.business == selectedEmp)
                {
                    empColl.Remove(emp);
                    //Remove it from the listbox too
                    employersListBox.Items.Remove(selectedEmp);
                    break;
                }
            }

            //Clear the items on form
            ClearPriorText();
        }

        //Clears Prior Employer Controls
        private void ClearPriorText()
        {
            foreach (Control con in priorEmplTabPage.Controls)
            {
                if (con is TextBox)
                {
                    con.Text = "";
                }
            }
        }

        //On Form Load
        private void AppFillerSuForm_Load(object sender, EventArgs e)
        {
        }

        //Employers List Box on Index Change
        private void employersListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedEmp = (string)employersListBox.SelectedItem;

            foreach (PriorEmployer emp in empColl)
            {
                //Find current match
                if (emp.business == selectedEmp)
                {
                    //Set all TextBoxes on form
                    businessAddr1TextBox.Text = emp.street;
                    businessAddr2TextBox.Text = emp.street2;
                    businessCityTextBox.Text = emp.city;
                    businessFromDateTimePicker.Value = emp.businessFrom;
                    businessManagerTextBox.Text = emp.businessManager;
                    businessPhoneTextBox.Text = emp.businessPhone;
                    businessReasonTextBox.Text = emp.businessReasonsForLeaving;
                    businessResponsTextBox.Text = emp.businessResponsibilities;
                    businessSalaryTextBox.Text = emp.businessSalary;
                    businessStateTextBox.Text = emp.state;
                    businessTextBox.Text = emp.business;
                    businessTitleTextBox.Text = emp.businessTitle;
                    businessToDateTimePicker.Value = emp.businessTo;
                    businessTypeTextBox.Text = emp.businessType;
                    businessZipTextBox.Text = emp.zip;
                }
            }
        }
    }
}